package com.na.flipcard.util;

import java.text.DecimalFormat;
import java.util.List;

import cn.bmob.BmobObject;

import com.na.game.GameManager;
import com.na.game.data.DataManager;
import com.na.game.platform.sns.SnsListener;
import com.na.game.platform.sns.SnsManager;
import com.na.game.util.Cache;
import com.na.game.util.GameException;
import com.na.game.util.Util;

public class GameUtil {

	private static final DecimalFormat df = new DecimalFormat("0.00");
	
	/**
	 * 0.1y=20p
	 * @param point
	 * @return
	 */
	public static float calcMoneyByPoint(int point) {
		if (point <= 0) {
			return 0f;
		}
		int n = point / 20 + (point % 20 > 0 ? 1 : 0);
		return n * 0.1f;
	}
	
	public static int calcPointByMoney(float money) {
		if (money <= 0) {
			return 0;
		}
		String result = df.format(money * 200);
		return (int) Math.ceil(Double.parseDouble(result));
	}
	
	public static void cacheBmob(final SnsListener listener) {
		if (Cache.getCache().get(GameConfigEx.CACHE_BMOB_SCORE) != null) {
			return;
		}
		SnsListener lsnr = new SnsListener() {
			@Override
			public void queryResult(List<BmobObject> result, GameException ex) {
				if (ex != null) { // query error
					ex.printStackTrace();
					return;
				}
				BmobObject bo = null;
				if (result != null && result.size() > 0) {
					bo = result.get(0);
					// fix local cache
					int highest = bo.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST);
					if (highest > GameManager.get(DataManager.class).get(GameConfigEx.DATA_SCORE_HIGHEST_ALL, 0)) {
						GameManager.get(DataManager.class).put(GameConfigEx.DATA_SCORE_HIGHEST_ALL, Integer.valueOf(highest));
					}
				} else if (GameManager.get(DataManager.class).get(GameConfigEx.DATA_SUBMIT_SCORE) == null) { // 未提交过分数
					bo = new BmobObject(GameConfigEx.BMOB_TABLE_SCORES);
				}
				if (bo != null) {
					Cache.getCache().put(GameConfigEx.CACHE_BMOB_SCORE, bo);
					String nickname = bo.getString(GameConfigEx.BMOB_TABLE_SCORES_COL_NICKNAME);
					if (nickname != null) { // compatible with old users
						GameManager.get(DataManager.class).put(GameConfigEx.DATA_MY_NICKNAME, nickname);
					}
					if (listener != null) {
						listener.queryResult(result, ex);
					}
				}
			}
		};
		GameManager.get(SnsManager.class).query(GameConfigEx.BMOB_TABLE_SCORES,
												lsnr,
												GameConfigEx.BMOB_TABLE_SCORES_COL_USERID, Util.getDeviceId(),
												GameConfigEx.BMOB_TABLE_SCORES_COL_NICKNAME, GameManager.get(DataManager.class).get(GameConfigEx.DATA_MY_NICKNAME)
		);
	}
	
}
